import React, {Component} from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import ReactMarkdown from 'react-markdown';
import {Card,Row,Col,Collapse,Rate,Icon,Button,Radio, Tag} from 'antd';
import isArray from 'lodash/isArray';
import forEach from 'lodash/forEach';

const Panel = Collapse.Panel;

import '../../../css/iconfont';
import style from './home.less';

import Loading from '../../../components/common/Loading';

import Charts1 from '../components/Charts1';
import Charts2 from '../components/Charts2';
import Charts3 from '../components/Charts3';
import Charts4 from '../components/Charts4';

import Profit from '../components/Profit';
import Risk from '../components/Risk';
import Activity from '../components/Activity';
import Consistency from '../components/Consistency';
import TeachV2 from '../components/TeachV2';
import General from '../components/General';

import Disclaimer from '../components/Disclaimer';



const collapseStyle={
  background:'none',
}
const panelStyle = {
  background:'rgba(51, 153, 255, 0.25)',
  marginBottom: 24,
  border: 0,
  overflow: 'hidden',
}

const checkout=({
  id,
  value,
  valueArr,
  comment
  })=>{
  let index,ii,arr,title=''
  if(valueArr){
    ii=checkIndex({
      num:value*1,
      numArr:valueArr
    })
    index=(ii||ii===0)?ii:valueArr.length
    arr=eval(`comment.${id}_${index}`)
  }else{
    arr=comment
  }
  title=arr[parseInt(Math.random()*(arr.length-1))].replace("_$_",value).replace("_#_",value)+'\n'
  return title
}

const checkIndex=({
  num=0,
  numArr=[20, 40, 60, 70]
  })=>{
  for(let i in numArr){
    if(numArr[i]>=num){
      return i*1
    }
  }
}

const record=(detail)=>{
  return {
      title:detail.specialText,
      info:{
        "trader":detail.trader,
        "dataDate":detail.closeOrder.dataDate,
        "orderId":detail.closeOrder.orderId,
        "symbol":detail.closeOrder.symbol,
        "tradeType":detail.closeOrder.tradeType,
        "price":detail.closeOrder.price,
        "quantity":detail.closeOrder.quantity,
        "fee":detail.closeOrder.fee,
        "timestamp":detail.closeOrder.timestamp,
        "tradeDate":detail.closeOrder.tradeDate,
        "comment":detail.commentClosedPos.comment,
        "score":detail.commentClosedPos.score
      },
      kLine:{
        "data":detail.Kline,
        "point":detail.closeOrder.closedPositionList
      },
      table:detail.closeOrder.closedPositionList
    }
}

const Cps=({info,notesConfig,details,recommendationsAll,putEducationFeed, gotoRetailEducationDetail,trader })=>{

  const getDetail=(details,type)=>{
    const detail=details&&details.length&&details.find(item=>item.specialType===type)
    if(detail&&detail.commentClosedPos){
      return record(detail)
    }
  }


  const profitProps={
    charts:{
      data:[
        {
          "name":"总盈亏",
          "value":info.scoreAllTimePnl&&info.scoreAllTimePnl.toFixed(2)||0
        },{
          "name":"平均收益率",
          "value":info.scorePnlEfficiency&&info.scorePnlEfficiency.toFixed(2)||0
        },{
          "name":"行情掌控能力",
          "value":info.scorePositionEfficiency&&info.scorePositionEfficiency.toFixed(2)||0
        },{
          "name":"天数胜率",
          "value":info.scoreWinningDayRatio&&info.scoreWinningDayRatio.toFixed(2)||0
        },{
          "name":"最长连赢天数",
          "value":info.scoreStreak&&info.scoreStreak.toFixed(2)||0
        },
      ]
    },
    notes:[
      {
        "name":"总盈亏",
        "value": `评估期内交易总盈利${info.allTimePnl&&info.allTimePnl.toFixed(2)||0}元，同期超过了${info.scoreAllTimePnl&&info.scoreAllTimePnl||0}%的用户，盈利金额越大盈利能力越强`
      },
      {
        "name":"平均收益率",
        "value":"盈利与交易资金比值，值越大表明资金的利用效率越高"
      },
      {
        "name":"行情掌控能力",
        "value":"值越大，把握行情能力越强，开平仓时机越好"
      },
      {
        "name":"天数胜率",
        "value":`统计周期内 ${info.winningDayRatio&&info.winningDayRatio*100||0} %天数都是盈利的，值越高发挥越稳定，心态越稳定`
      },
      {
        "name":"最长连赢天数",
        "value":`统计周期内最长连赢了 ${info.streak&&info.streak||0} 天，值为 ${info.scoreStreak&&info.scoreStreak.toFixed(2)||0} 分，分数越高盈利能力越强，判断趋势能力越强`
      }
    ],
    profitRecord:getDetail(details,'max_profit'),
    lossRecord:getDetail(details,'max_loss'),
    pnlEfficiencyRecord:getDetail(details,'max_pnl_efficiency'),
  }
  const riskProps={
    charts:[
      {
        data :[
          {
            name: '损失控制能力',
            value: parseInt(info.scoreStdNegEff*1)
          }
        ],
        color:['#5AB1EF']
      },
      {
        data :[
          {
            name: '左手交易倾向',
            value: parseInt(info.scorePotentialRisk*1)
          }
        ],
        color:['#FFB980']
      },
      {
        data :[
          {
            name: '风险收益能力',
            value: parseInt(info.scoreRiskOverPnl*1)
          }
        ],
        color: ['#D87A80']
      },
      {
        data :[
          {
            name: '风险厌恶度',
            value: parseInt(info.scoreEffVar*1)
          }
        ],
        color:['#8D98B3']
      }
    ],
    notes:[
      {
        "name":"损失控制能力",
        "value":"值越大，表明说明风控水平越稳定，具有较一致并可控的损失预期"
      },
      {
        "name":"左手交易倾向",
        "value":"值越小，表明越容易导致亏损交易，可能经常进行左手交易"
      },
      {
        "name":"风险收益能力",
        "value":"该指标评估相同风险水平下取得收益的能力，值越大表明同风险水平下获取收益的能力越强s"
      },
      {
        "name":"风险厌恶度",
        "value":"评估可能的风险损失，值越大，可能的损失越小"
      }
    ],
    recordRecord:getDetail(details,'max_potential_risk'),
    riskRecord:getDetail(details,'max_risk_over_pnl'),
    positionEfficiencyRecord:getDetail(details,'max_position_efficiency'),
  }
  const activityProps={
    charts:{
      data : [
        {
          name: `交易天数${info.tradeDays&&info.tradeDays||0}天`,
          value: info.scoreTradeDays&&info.scoreTradeDays.toFixed(2)||0
        }, {
          name:`交易次数${info.tradeCount&&info.tradeCount||0}次`,
          value: info.scoreTradeCount&&info.scoreTradeCount.toFixed(2)||0
        }, {
          name:`交易日总数${info.tradeLife&&info.tradeLife||0}天`,
          value: info.scoreTradeLife&&info.scoreTradeLife.toFixed(2)||0
        }, {
          name:`活跃比率${info.activeRatio&&info.activeRatio.toFixed(2)||0}`,
          value: info.scoreActiveRatio&&info.scoreActiveRatio.toFixed(2)||0
        },
      ]
    },
    notes:[
      {
        "name":"交易天数",
        "value":`评估期内交易了${info.tradeDays&&info.tradeDays||0}天，同期超过了${info.scoreTradeDays&&info.scoreTradeDays.toFixed(2)||0}%的用户，天数越多越活跃`
      },
      {
        "name":"交易次数",
        "value":`评估期内交易了${info.tradeCount&&info.tradeCount||0}次，同期超过了${info.scoreTradeCount&&info.scoreTradeCount.toFixed(2)||0}%的用户，次数越多越活越活跃`
      },
      {
        "name":"交易日总数",
        "value":`期间共${info.tradeLife&&info.tradeLife||0}个交易日`
      },
      {
        "name":"活跃比率",
        "value":`交易天数（${info.tradeDays&&info.tradeDays||0}）与交易日总数（${info.tradeLife&&info.tradeLife||0}）的比值，比值为${info.activeRatio&&info.activeRatio.toFixed(2)||0}，同期超过了${info.scoreActiveRatio&&info.scoreActiveRatio.toFixed(2)||0}%的用户，越高越活跃`
      }
    ],
  }
  const consistencyProps={
    charts:{
      name :"稳定性",
      data : [
        [{
          value:info.scoreEffSortinoRatio&&info.scoreEffSortinoRatio.toFixed(2)||0,
          name:'盈利稳定性得分'
        }, {
          value:100-(info.scoreEffSortinoRatio&&info.scoreEffSortinoRatio.toFixed(2)||0),
          name:'invisible'
        }],
        [{
            value:info.scoreStdNegEff&&info.scoreStdNegEff.toFixed(2)||0,
            name:'损失稳定性得分'
        },
        {
            value:100-(info.scoreStdNegEff&&info.scoreStdNegEff.toFixed(2)||0),
            name:'invisible'
        }],
        [{
            value:info.scoreStdQuantity&&info.scoreStdQuantity.toFixed(2)||0,
            name:'交易数量稳定性得分'
        },
        {
            value:100-(info.scoreStdQuantity&&info.scoreStdQuantity.toFixed(2)||0),
            name:'invisible'
        }],
        [{
            value:info.scoreStdVolume&&info.scoreStdVolume.toFixed(2)||0,
            name:'交易量稳定性得分'
        },
        {
            value:100-(info.scoreStdVolume&&info.scoreStdVolume.toFixed(2)||0),
            name:'invisible'
        }]
      ]
    },
    notes:[
      {
        "name":"盈利稳定性",
        "value":"该指标考察盈亏波动情况，值越大，赚钱能力越稳定"
      },
      {
        "name":"损失稳定性",
        "value":"该指标考察损失控制能力，值越大，表明说明风控水平越稳定"
      },
      {
        "name":"交易数量稳定性",
        "value":`评估期内交易数量波动为${info.stdQuantity&&info.stdQuantity.toFixed(2)||0}，同期超过了${info.scoreStdQuantity&&info.scoreStdQuantity.toFixed(2)||0}%的用户，波动量越小风格越稳定`
      },
      {
        "name":"交易量稳定性",
        "value":`评估期内交易量波动为${info.stdVolume&&info.stdVolume.toFixed(2)||0}，同期超过了${info.scoreStdVolume&&info.scoreStdVolume.toFixed(2)||0}%的用户，波动量越小风格越稳定`
      }
    ]
  }
  const teachV2Props={
    trader,
    putEducationFeed,
    gotoRetailEducationDetail,
    recommendationsAll,
    notesv2:recommendationsAll.education
  }
  const panelArr=[
    {
      title:"盈利能力",
      icon:'meiyuan',
      subTitle:()=>{
        let titles=''
        const subTitles=[
          {
            id:"profitability",
            value:info.profitability&&info.profitability.toFixed(2)||0,
            valueArr:notesConfig.dimension_pivots.profitability,
            comment:notesConfig.comment_text.profitability
          },
          {
            id:"eff_sharpe_ratio",
            value:info.effSharpeRatio&&info.effSharpeRatio.toFixed(2)||0,
            valueArr:notesConfig.feature_pivots.eff_sharpe_ratio,
            comment:notesConfig.comment_text.eff_sharpe_ratio
          },
          {
            id:"pnl_efficiency",
            value:info.pnlEfficiency&&info.pnlEfficiency.toFixed(2)||0,
            score:info.scorePnlEfficiency&&info.scorePnlEfficiency.toFixed(2)||0,
            trigger:notesConfig.diagnosis_features.pnl_efficiency.trigger,
            comment:notesConfig.diagnosis_features.pnl_efficiency.comments
          },
          {
            id:"win_ratio",
            value:info.winRatio&&info.winRatio.toFixed(2)||0,
            score:info.scoreWinRatio&&info.scoreWinRatio.toFixed(2)||0,
            trigger:notesConfig.diagnosis_features.win_ratio.trigger,
            comment:notesConfig.diagnosis_features.win_ratio.comments
          },
          {
            id:"streak",
            value:info.streak&&info.streak.toFixed(2)||0,
            score:info.scoreStreak&&info.scoreStreak.toFixed(2)||0,
            trigger:notesConfig.diagnosis_features.streak.trigger,
            comment:notesConfig.diagnosis_features.streak.comments
          },
          {
            id:"all_time_pnl",
            value:info.allTimePnl&&info.allTimePnl.toFixed(2)||0,
            score:info.scoreAllTimePnl&&info.scoreAllTimePnl.toFixed(2)||0,
            trigger:notesConfig.diagnosis_features.all_time_pnl.trigger,
            comment:notesConfig.diagnosis_features.all_time_pnl.comments
          }
        ]
        if(notesConfig){
          subTitles.map((item,i)=>{
            if(item.value&&((item.trigger&&item.score<item.trigger)||!item.trigger)){
              titles+=checkout(item)
            }
          })
        }
        return titles
      },
      rate:info.profitability&&(parseInt(info.profitability/10)/2),
      children:<Profit {...profitProps} />
    },
    {
      title:"风险控制",
      icon:'fengxian',
      subTitle:()=>{
        let titles=''
        const subTitles=[
          {
            id:"risk_control",
            value:info.riskControl&&info.riskControl.toFixed(2)||0,
            valueArr:notesConfig.dimension_pivots.risk_control,
            comment:notesConfig.comment_text.risk_control
          },
          {
            id:"potential_risk",
            value:info.potentialRisk&&info.potentialRisk.toFixed(2)||0,
            valueArr:notesConfig.feature_pivots.potential_risk,
            comment:notesConfig.comment_text.potential_risk
          },
          {
            id:"risk_over_pnl",
            value:info.riskOverPnl&&info.riskOverPnl.toFixed(2)||0,
            valueArr:notesConfig.feature_pivots.risk_over_pnl,
            comment:notesConfig.comment_text.risk_over_pnl
          },
          {
            id:"std_neg_roi",
            value:info.stdNegRoi&&info.stdNegRoi.toFixed(2)||0,
            score:info.scoreStdNegRoi&&info.scoreStdNegRoi.toFixed(2)||0,
            trigger:notesConfig.diagnosis_features.std_neg_roi.trigger,
            comment:notesConfig.diagnosis_features.std_neg_roi.comments
          }
        ]
        if(notesConfig){
          subTitles.map((item,i)=>{
            if(item.value&&((item.trigger&&item.score<item.trigger)||!item.trigger)){
              titles+=checkout(item)
            }
          })
        }
        return titles
      },
      rate:info.riskControl&&(parseInt(info.riskControl/10)/2),
      children:<Risk {...riskProps} />
    },
    {
      title:"活跃度",
      icon:'huoyuedu',
      subTitle:()=>{
        let titles=''
        const subTitles=[
          {
            id:"activity",
            value:info.activity&&info.activity.toFixed(2)||0,
            valueArr:notesConfig.dimension_pivots.activity,
            comment:notesConfig.comment_text.activity
          }
        ]
        if(notesConfig){
          subTitles.map((item,i)=>{
            if(item.value&&((item.trigger&&item.score<item.trigger)||!item.trigger)){
              titles+=checkout(item)
            }
          })
        }
        return titles
      },
      rate:info.activity&&(parseInt(info.activity/10)/2),
      children:<Activity {...activityProps} />
    },
    {
      title:"稳定性",
      icon:'wending',
      subTitle:()=>{
        let titles=''
        const subTitles=[
          {
            id:"consistency",
            value:info.consistency&&info.consistency.toFixed(2)||0,
            valueArr:notesConfig.dimension_pivots.consistency,
            comment:notesConfig.comment_text.consistency
          }
        ]
        if(notesConfig){
          subTitles.map((item,i)=>{
            if(item.value&&((item.trigger&&item.score<item.trigger)||!item.trigger)){
              titles+=checkout(item)
            }
          })
        }
        return titles
      },
      rate:info.consistency&&(parseInt(info.consistency/10)/2),
      children:<Consistency {...consistencyProps} />
    },
    {
      title:"智能教学",
      icon:'jiaoxue',
      subTitle:()=>{
        let subTitle = '';
        if (recommendationsAll 
        && isArray(recommendationsAll.education)
        && recommendationsAll.education.length > 0
        && isArray(recommendationsAll.education[0].reasons)
        && recommendationsAll.education[0].reasons.length > 0) {
          const lastIndex = recommendationsAll.education[0].reasons.length - 1;
          if (recommendationsAll.education[0].reasons[lastIndex].reason) {
            subTitle = recommendationsAll.education[0].reasons[lastIndex].reason;
          }
        }
        return subTitle;
      },
      children:<TeachV2 {...teachV2Props} />,
    },
  ]

  let lastKey=[],openKey
  const  callback=(key)=> {
    if(key.length>lastKey.length){
      openKey=key[key.length-1]
      switch(openKey){
        case '1':_paq.push(['trackEvent','散户',	'投顾界面',	'盈利能力',	trader]);break;
        case '2':_paq.push(['trackEvent','散户',	'投顾界面',	'风控能力',	trader]);break;
        case '3':_paq.push(['trackEvent','散户',	'投顾界面',	'活跃度',	trader]);break;
        case '4':_paq.push(['trackEvent','散户',	'投顾界面',	'稳定性',	trader]);break;
        case '5':_paq.push(['trackEvent','散户',	'投顾界面',	'智能教学',	trader]);break;
      }
    }
    lastKey=key
  }
  return (
    <Collapse
       bordered={false}
       style={collapseStyle}
       onChange={callback}
      >
        {
          panelArr.map((item,i)=>(
            <Panel
              header={
                <div className={style.title} title={item.title}>
                  <span><i className={`icon iconfont icon-thfx-${item.icon}`}></i>{item.title}</span>
                  {
                    item.rate?(
                      <Rate
                        disabled
                        defaultValue={item.rate}
                        allowHalf
                        style={{ fontSize: 28 }}
                       />
                    ):null
                  }

                   <ReactMarkdown source={item.subTitle()||''} />

                </div>}
              key={String(i+1)}
              style={panelStyle}
              bordered={true}
              >
                {item.children}
            </Panel>
          ))
        }


    </Collapse>
  )
}



const Retail = ({dispatch,retail,location}) =>{
  const {
    msg,
    info={},
    notesConfig={},
    trend=[],
    details=[],
    recommendationsAll={},
    fdtScore={},
    profitability={},
    riskControl={},
    activity={},
    consistency={},
  }=retail
  if(info.trader){

    const putEducationFeed = (payload) =>{
      payload.trader=info.trader
      dispatch({
        type:'retail/putEducationFeed',
        payload,
      })
    }

    const gotoRetailEducationDetail = (payload) => {
      payload.trader=info.trader
      dispatch({
        type:'retail/gotoRetailEducationDetail',
        payload,
      })
    }

    const labels = recommendationsAll.index.labels;
    forEach(recommendationsAll.index.education, (item) => {
      if (labels.indexOf(item.reason) === -1 && item.reason !== null && item.reason.length > 0) {
        labels.push(item.reason);
      }
    })

  	return (
  		<div className={style.retail}>
        <General info={info} trader={location.query.trader} trend={trend} notesConfig={notesConfig} labels={labels} fdtScore={fdtScore} />
        <Cps
          info={info}
          notesConfig={notesConfig}
          details={details}
          recommendationsAll={recommendationsAll}
          putEducationFeed={putEducationFeed}
          gotoRetailEducationDetail={gotoRetailEducationDetail}
          trader={info.trader}
        />
        <Disclaimer />
  		</div>
  	)
  }else{
    if(location.query.trader){
      if(msg){
        return <div className={style.msg}>{msg}</div>
      }else{
        return <Loading loading={true}  />
      }
    }else{
      return <div className={style.msg}>没有指定的用户</div>
    }

  }

}

Retail.propTypes = {
};

export default connect(({retail}) => ({retail}))(Retail);
